package cn.mesmile.juc.pool;

import cn.hutool.core.util.RandomUtil;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author zb
 * @date 2021/8/17 23:17
 * @Description 线程创建
 */
public class ThreadPoolDemo {

    public static void main(String[] args) {
        // 5 个线程处理 10 个任务
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        // 1 个线程处理 10个任务
//        ExecutorService executorService = Executors.newSingleThreadExecutor();
        // 动态扩容线程
//        ExecutorService executorService = Executors.newCachedThreadPool();
        CountDownLatch countDownLatch = new CountDownLatch(10);
        try {
            for (int i = 0; i < 10; i++) {
                executorService.execute(()->{
                    if (true){
                        try {
                            Thread.sleep(RandomUtil.randomInt(10,200));
                            throw new RuntimeException("test");
                        } catch (Exception e) {
                            e.printStackTrace();
                            // 发生异常记得 减去 1 否则，countDownLatch.await() 会阻塞
                            countDownLatch.countDown();
                            return;
                        }
                    }
                    System.out.println(Thread.currentThread().getName()+" 处理业务");
                    countDownLatch.countDown();
                });
            }

            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }

    }
}
